// formateDate格式化工具
export function formateDate(date, rule) {
  let fmt = rule || "yyyy-MM-dd hh:mm:ss";
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, date.getFullYear());
  }
  const o = {
    // 'y+': date.getFullYear(),
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const val = o[k] + "";
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? val : ("00" + val).substr(val.length)
      );
    }
  }
  return fmt;
}

export function convertHtmlToUniApp(html) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, "text/html");
  const body = doc.body;
  const uniAppNodes = convertNodesToUniApp(body.childNodes);
  return uniAppNodes.join("");
}
function convertNodesToUniApp(nodes) {
  const result = [];
  let lastNodeType = null;
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    if (node.nodeType === Node.TEXT_NODE) {
      const textContent = node.textContent.trim();
      if (textContent) {
        // 判断文本内容是否为空，为空则不处理
        const lines = textContent.split(/\r?\n/);
        for (let j = 0; j < lines.length; j++) {
          const line = lines[j];
          if (line) {
            // 判断文本行是否为空，为空则不处理
            const isSingleChar = line.length === 1;
            const isShortWord = line.split(' ').reduce((acc, cur) => acc && (cur.length <= 2), true);
            if (!isSingleChar && !isShortWord) {
              // 判断文本行是否是单个字符或短单词，是则不处理
              result.push(`<p style="text-indent: 2em;">${line}</p>`);
              lastNodeType = Node.TEXT_NODE;
            }
          }
        }
      }
    } else if (node.nodeType === Node.ELEMENT_NODE) {
      const tagName = node.tagName.toLowerCase();
      const attrs = getAttributes(node.attributes);
      const children = convertNodesToUniApp(node.childNodes);
      if (tagName === 'figure') {
        result.push(`<view${attrs}>${children.join("")}</view>`);
        lastNodeType = Node.ELEMENT_NODE;
      } else {
        if (lastNodeType === Node.TEXT_NODE) {
          result.push('<br/>'); // 上一个节点为文本节点，则需要插入一个换行符
        }
        result.push(`<${tagName}${attrs}>${children.join("")}</${tagName}>`);
        lastNodeType = Node.ELEMENT_NODE;
      }
    }
  }
  return result;
}
function getAttributes(attributes) {
  if (!attributes || attributes.length === 0) {
    return "";
  }
  const result = [];
  for (let i = 0; i < attributes.length; i++) {
    const attr = attributes[i];
    const name = attr.name;
    const value = attr.value;
    result.push(` ${name}="${value}"`);
  }
  return result.join("");
}